package com.shyt.security;


import com.shyt.util.CheckTokenFilterUtill;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/***
 * 权限总认证
 */
@Slf4j
@Component
public class SpringSecritAuthUtil extends WebSecurityConfigurerAdapter {
    /**** 登录成功处理器 ****/
    @Autowired
    LoginSuccessUtil loginSuccessUtil;

    /**** 登录失败处理器 ****/
    @Autowired
    LoginFailUtil loginFailUtil;

    /**** 登录权限认证失败处理器 ****/
    @Autowired
    AccessRejectUtil accessRejectUtil;

    /**** 登录匿名认证拒绝处理器 ****/
    @Autowired
    NMRZRejectUtil nmrzRejectUtil;
    /**** 登录匿名认证拒绝处理器 ****/

    @Autowired
    AuthUserDetailUtil authUserDetailUtil;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    CheckTokenFilterUtill checkTokenFilterUtill;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(
                checkTokenFilterUtill, UsernamePasswordAuthenticationFilter.class);

        log.info("进入登录拦截处理__________________________________");

        http.formLogin()

                .loginProcessingUrl("/api/user/login")// 设置登录验证成功或失败后的的跳转地址
                .successHandler(loginSuccessUtil)
                .failureHandler(loginFailUtil)
                .usernameParameter("username")//前端登录传输账号的key
                .passwordParameter("password")//前端登录传输账号的key// 禁用csrf防御机制
                .and().csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/api/user/login").permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(nmrzRejectUtil)
                .accessDeniedHandler(accessRejectUtil)
                .and().cors();//开启跨域配置

        log.info("登录认证结束——————————————————————————————————————————");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(authUserDetailUtil).passwordEncoder(bCryptPasswordEncoder);
    }
}
